import { NextRequest, NextResponse } from "next/server";
import { SqliteDatabase } from "@/lib/sqlite-database";

export async function POST(request: NextRequest) {
  try {
    const database = new SqliteDatabase();
    
    // 获取当前位置参数总数
    const totalRowsStmt = database['db'].prepare('SELECT COUNT(*) as total FROM position_parameters');
    const allPositionParams = totalRowsStmt.get() as { total: number };
    const totalRows = allPositionParams.total;
    
    console.log(`当前位置参数总行数: ${totalRows}`);
    
    if (totalRows <= 1400) {
      return NextResponse.json({
        success: true,
        message: `当前只有 ${totalRows} 行数据，无需删除`,
        deletedCount: 0,
        remainingCount: totalRows
      });
    }
    
    // 获取前1400行的最大ID
    const idsStmt = database['db'].prepare(`
      SELECT id FROM position_parameters 
      ORDER BY id 
      LIMIT 1400
    `);
    const result = idsStmt.all() as { id: number }[];
    
    if (result.length === 0) {
      return NextResponse.json({
        success: false,
        message: "无法获取前1400行数据",
      }, { status: 500 });
    }
    
    const maxIdToKeep = result[result.length - 1].id;
    console.log(`保留ID <= ${maxIdToKeep} 的数据`);
    
    // 删除ID大于maxIdToKeep的所有记录
    const deleteStmt = database['db'].prepare(`
      DELETE FROM position_parameters 
      WHERE id > ?
    `);
    const deleteResult = deleteStmt.run(maxIdToKeep);
    
    // 获取删除后的总数
    const afterCountStmt = database['db'].prepare('SELECT COUNT(*) as total FROM position_parameters');
    const afterCount = afterCountStmt.get() as { total: number };
    const deletedCount = totalRows - afterCount.total;
    
    console.log(`删除了 ${deletedCount} 行数据，剩余 ${afterCount.total} 行`);
    
    return NextResponse.json({
      success: true,
      message: `成功删除第1400行之后的数据`,
      deletedCount,
      remainingCount: afterCount.total,
      maxIdKept: maxIdToKeep,
      originalTotal: totalRows
    });
    
  } catch (error) {
    console.error("清理位置参数数据时出错:", error);
    return NextResponse.json(
      { 
        success: false, 
        message: "清理位置参数数据过程中发生错误",
        error: error instanceof Error ? error.message : "未知错误"
      },
      { status: 500 }
    );
  }
} 